<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 头部警告区 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数！" :closable="false" show-icon type="warning"></el-alert>
      <!-- 选择商品分类 -->
      <el-row>
        <el-col>
          <!-- 级联选择框 -->
          <div class="block">
            <span class="demonstration">选择商品分类：</span>
            <el-cascader
              v-model="shopSelectedKeys"
              :options="shopList"
              :props="shopPorps"
              @change="shopChange"
            ></el-cascader>
          </div>
        </el-col>
      </el-row>
      <!-- tab栏区 -->
      <template>
        <el-tabs v-model="activeName" @tab-click="handleTabClick">
          <!-- 添加动态参数的面板 -->
          <el-tab-pane label="动态参数" name="many">
            <el-button
              type="primary"
              size="mini"
              :disabled="isBtnDisabled"
              @click="setSelDialog"
            >添加参数</el-button>
            <!-- 表格 -->
            <el-table :data="manySelList" border style="width: 100%">
              <el-table-column type="expand">
                <template slot-scope="props">
                  <el-tag
                    @close="inputVisibleClosed(index,props.row)"
                    closable
                    v-for="(item, index) in props.row.attr_vals"
                    :key="index"
                  >{{item}}</el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="props.row.inputVisible"
                    v-model="props.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(props.row)"
                    @blur="handleInputConfirm(props.row)"
                  ></el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInputVisible(props.row)"
                  >+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type="index"></el-table-column>
              <el-table-column prop="attr_name" label="参数名称"></el-table-column>
              <el-table-column prop="address" label="操作">
                <template slot-scope="scope">
                  <!-- 编辑 -->
                  <el-button
                    size="mini"
                    type="primary"
                    icon="el-icon-edit"
                    @click="showEditDialog(scope.row)"
                  >编辑</el-button>
                  <!-- 删除 -->
                  <el-button
                    size="mini"
                    type="danger"
                    icon="el-icon-delete"
                    @click="deleteDiaLog(scope.row)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <!-- 添加静态属性的面板 -->
          <el-tab-pane label="静态属性" name="only">
            <el-button
              type="primary"
              size="mini"
              :disabled="isBtnDisabled"
              @click="setSelDialog"
            >添加属性</el-button>
            <!-- 静态属性的表格 -->
            <el-table :data="onlySelList" border style="width: 100%">
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag
                    @close="inputVisibleClosed(index,scope.row)"
                    closable
                    v-for="(item, index) in scope.row.attr_vals"
                    :key="index"
                  >{{item}}</el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  ></el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInputVisible(scope.row)"
                  >+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type="index"></el-table-column>
              <el-table-column prop="attr_name" label="参数名称"></el-table-column>
              <el-table-column prop="address" label="操作">
                <template slot-scope="scope">
                  <!-- 编辑 -->
                  <el-button
                    size="mini"
                    type="primary"
                    icon="el-icon-edit"
                    @click="showEditDialog(scope.row)"
                  >编辑</el-button>
                  <!-- 删除 -->
                  <el-button
                    size="mini"
                    type="danger"
                    icon="el-icon-delete"
                    @click="deleteDiaLog(scope.row)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </template>
    </el-card>
    <!-- 添加参数的弹出层 -->
    <el-dialog
      :title="'添加'+titleText"
      :visible.sync="selDialogVisible"
      width="50%"
      @close="selDialogClosed"
    >
      <!-- 添加参数的对话框  -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="selDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数的弹出层 -->
    <el-dialog
      title="修改参数"
      :visible.sync="updateDialogVisible"
      width="50%"
      @close="updateDialogClosed"
    >
      <!-- 修改参数的对话框  -->
      <el-form
        :model="updateForm"
        :rules="addFormRules"
        ref="updateFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="updateForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { truncate } from "fs";
import { async } from "q";
export default {
  data() {
    return {
      shopList: [],
      shopPorps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      shopSelectedKeys: [],
      // 被激活的tab栏
      activeName: "many",
      // 需要渲染的动态参数
      manySelList: [],
      // 需要渲染的静态参数
      onlySelList: [],
      // 控制添加参数的弹出层
      selDialogVisible: false,
      // 添加参数的表单数据对象
      addForm: {
        attr_name: ""
      },
      // 添加表单的验证规则
      addFormRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" }
        ]
      },
      // 控制修改参数的弹出层
      updateDialogVisible: false,
      // 修改参数的表单数据对象
      updateForm: {
        attr_name: ""
      },
      // 控制new tag文本框的切换
      inputVisible: false,
      // 文本框的数据
      inputValue: null
    };
  },
  methods: {
    async getShopList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.shopList = res.data;
    },
    async getShopListbyId() {
      const { data: res } = await this.$http.get(
        "categories/" + this.cateId + "/attributes",
        {
          params: {
            sel: this.activeName
          }
        }
      );
      if (res.meta.status !== 200) return;

      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        console.log(item.attr_vals);
        for (var i = 0; i < item.attr_vals.length; i++) {
          if (!item.attr_vals[i]) {
            item.attr_vals.splice(i, 1);
            i = i - 1;
          }
        }
        console.log(item.attr_vals);
        item.inputVisible = false;
        item.inputValue = null;
      });
      if (this.activeName == "many") {
        this.manySelList = res.data;
      } else {
        this.onlySelList = res.data;
      }
    },
    shopChange(v) {
      // console.log(v);
      if (v.length != 3) {
        this.shopSelectedKeys = [];
        this.manySelList = [];
        this.onlySelList = [];
        return;
      }
      this.getShopListbyId();
    },
    handleTabClick() {
      this.getShopListbyId();
    },
    setSelDialog() {
      this.selDialogVisible = true;
    },
    selDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    // 点击按钮添加参数
    addParams() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$message.error("添加失败");
        const { data: res } = await this.$http.post(
          "categories/" + this.cateId + "/attributes",
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        );
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
        this.$message.success(res.meta.msg);
        this.selDialogVisible = false;
        this.getShopListbyId();
      });
    },
    showEditDialog(v) {
      this.updateForm = v;

      this.updateDialogVisible = true;
    },
    updateDialogClosed() {
      this.updateForm = {};
    },
    updateParams() {
      this.$refs.updateFormRef.validate(async volid => {
        if (!volid) return this.$message.error("输入参数错误");
        const { data: res } = await this.$http.put(
          "categories/" +
            this.cateId +
            "/attributes/" +
            this.updateForm.attr_id,
          {
            attr_name: this.updateForm.attr_name,
            attr_sel: this.activeName
          }
        );
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.updateDialogVisible = false;
        this.$message.success(res.meta.msg);
      });
    },
    async deleteDiaLog(v) {
      const data = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (data !== "confirm") return this.$message.info("取消删除");
      const { data: res } = await this.$http.delete(
        "categories/" + v.cat_id + "/attributes/" + v.attr_id
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.getShopListbyId();
      return this.$message.success(res.meta.msg);
    },
    showInputVisible(v) {
      v.inputVisible = true;
      // 让文本框自动获得焦点
      // $nextTick 代表的是页面上的元素被重新渲染之后才执行回调函数
      // 如果没有在页面元素重新渲染之后执行,就可能会报错
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 文本失去焦点或摁下enter触发
    handleInputConfirm(v) {
      if (v.inputValue.trim().length === 0) {
        v.inputVisible = false;
        v.inputValue = "";
        return;
      }
      let inputValue = v.inputValue;
      if (inputValue) {
        v.attr_vals.push(inputValue.trim());
      }
      v.inputValue = "";
      v.inputVisible = false;
      this.putCateDate(v);
    },
    // 将对attr_vals的操作同步到数据库
    async putCateDate(v) {
      const { data: res } = await this.$http.put(
        "categories/" + v.cat_id + "/attributes/" + v.attr_id,
        {
          attr_name: v.attr_name,
          attr_sel: v.attr_sel,
          attr_vals: v.attr_vals.join(" ")
        }
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
    },
    // 删除对应的参数可选项
    inputVisibleClosed(index, v) {
      console.log(index, v);
      v.attr_vals.splice(v.attr_vals.indexOf(index), 1);
      console.log(v.attr_vals);
      this.putCateDate(v);
    }
  },
  created() {
    this.getShopList();
  },
  computed: {
    cateId() {
      if (this.shopSelectedKeys.length === 3) {
        return this.shopSelectedKeys[2];
      }
      return null;
    },
    isBtnDisabled() {
      if (this.shopSelectedKeys.length != 3) {
        return true;
      }
      return false;
    },
    titleText() {
      if (this.activeName === "many") {
        return "动态参数";
      }
      return "静态属性";
    }
  }
};
</script>

<style lang="less" scoped>
.el-row {
  margin-top: 15px;
}
.el-tag {
  margin: 7px;
}
.input-new-tag {
  width: 100px;
}
</style>
